// ==================== 审计追踪系统演示程序 ====================
// 文件功能：演示三级权限管理、数据导出和插件系统的核心功能
// 作者：审计追踪系统开发团队
// 版本：1.0.0

#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QTextEdit>
#include <QComboBox>
#include <QLineEdit>
#include <QMessageBox>
#include <QFileDialog>
#include <QDir>
#include <QDebug>

#include "permissionmanager.h"
#include "dataexporter.h"
#include "pluginsystem.h"
#include "auditlogger.h"

/**
 * @brief 演示窗口类
 * 展示系统的各项增强功能
 */
class DemoWindow : public QWidget
{
    Q_OBJECT

public:
    explicit DemoWindow(QWidget *parent = nullptr);

private slots:
    void testPermissionSystem();
    void testDataExport();
    void testPluginSystem();
    void clearLog();

private:
    // UI组件
    QTextEdit *m_logOutput;
    QComboBox *m_userCombo;
    QComboBox *m_permissionCombo;
    QComboBox *m_exportFormatCombo;
    QLineEdit *m_exportPathEdit;
    
    // 核心组件
    PermissionManager *m_permissionManager;
    DataExporter *m_dataExporter;
    PluginSystem *m_pluginSystem;
    AuditLogger *m_auditLogger;
    
    // 辅助方法
    void setupUI();
    void setupTestData();
    void logMessage(const QString &message);
    void createTestAuditRecords();
};

DemoWindow::DemoWindow(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle("审计追踪系统功能演示 v1.0.0");
    setMinimumSize(800, 600);
    
    // 初始化核心组件
    m_permissionManager = new PermissionManager(this);
    m_dataExporter = new DataExporter(this);
    m_pluginSystem = new PluginSystem(this);
    m_auditLogger = new AuditLogger(this);
    
    // 初始化审计日志系统
    QString dbPath = QDir::tempPath() + "/demo_audit.db";
    if (m_auditLogger->initialize(dbPath, "demo_password")) {
        logMessage("✅ 审计日志系统初始化成功");
    } else {
        logMessage("❌ 审计日志系统初始化失败");
    }
    
    setupUI();
    setupTestData();
    createTestAuditRecords();
    
    logMessage("🚀 审计追踪系统演示程序启动完成");
    logMessage("📋 请点击下方按钮测试各项功能");
}

void DemoWindow::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 标题
    QLabel *titleLabel = new QLabel("审计追踪系统增强功能演示", this);
    titleLabel->setStyleSheet("font-size: 18px; font-weight: bold; color: #2c3e50; margin: 10px;");
    titleLabel->setAlignment(Qt::AlignCenter);
    mainLayout->addWidget(titleLabel);
    
    // 功能测试区域
    QHBoxLayout *testLayout = new QHBoxLayout();
    
    // 权限管理测试
    QVBoxLayout *permissionLayout = new QVBoxLayout();
    permissionLayout->addWidget(new QLabel("三级权限管理测试:", this));
    
    m_userCombo = new QComboBox(this);
    m_userCombo->addItems({"admin", "operator", "viewer", "test_user"});
    permissionLayout->addWidget(m_userCombo);
    
    m_permissionCombo = new QComboBox(this);
    m_permissionCombo->addItems({"AUDIT_VIEW", "AUDIT_EXPORT", "USER_MANAGEMENT", "PLUGIN_MANAGE"});
    permissionLayout->addWidget(m_permissionCombo);
    
    QPushButton *testPermissionBtn = new QPushButton("测试权限系统", this);
    testPermissionBtn->setStyleSheet("background-color: #3498db; color: white; padding: 8px; border-radius: 4px;");
    connect(testPermissionBtn, &QPushButton::clicked, this, &DemoWindow::testPermissionSystem);
    permissionLayout->addWidget(testPermissionBtn);
    
    testLayout->addLayout(permissionLayout);
    
    // 数据导出测试
    QVBoxLayout *exportLayout = new QVBoxLayout();
    exportLayout->addWidget(new QLabel("高级数据导出测试:", this));
    
    m_exportFormatCombo = new QComboBox(this);
    m_exportFormatCombo->addItems({"CSV", "JSON", "XML", "HTML"});
    exportLayout->addWidget(m_exportFormatCombo);
    
    m_exportPathEdit = new QLineEdit(this);
    m_exportPathEdit->setPlaceholderText("选择导出路径...");
    exportLayout->addWidget(m_exportPathEdit);
    
    QPushButton *browseBtn = new QPushButton("浏览...", this);
    connect(browseBtn, &QPushButton::clicked, [this]() {
        QString format = m_exportFormatCombo->currentText().toLower();
        QString fileName = QFileDialog::getSaveFileName(this, "保存导出文件", 
                                                       QDir::homePath() + "/demo_export." + format,
                                                       QString("%1 Files (*.%2)").arg(format.toUpper(), format));
        if (!fileName.isEmpty()) {
            m_exportPathEdit->setText(fileName);
        }
    });
    exportLayout->addWidget(browseBtn);
    
    QPushButton *testExportBtn = new QPushButton("测试数据导出", this);
    testExportBtn->setStyleSheet("background-color: #27ae60; color: white; padding: 8px; border-radius: 4px;");
    connect(testExportBtn, &QPushButton::clicked, this, &DemoWindow::testDataExport);
    exportLayout->addWidget(testExportBtn);
    
    testLayout->addLayout(exportLayout);
    
    // 插件系统测试
    QVBoxLayout *pluginLayout = new QVBoxLayout();
    pluginLayout->addWidget(new QLabel("插件系统测试:", this));
    
    QPushButton *testPluginBtn = new QPushButton("测试插件系统", this);
    testPluginBtn->setStyleSheet("background-color: #e74c3c; color: white; padding: 8px; border-radius: 4px;");
    connect(testPluginBtn, &QPushButton::clicked, this, &DemoWindow::testPluginSystem);
    pluginLayout->addWidget(testPluginBtn);
    
    testLayout->addLayout(pluginLayout);
    
    mainLayout->addLayout(testLayout);
    
    // 日志输出区域
    QLabel *logLabel = new QLabel("系统日志输出:", this);
    logLabel->setStyleSheet("font-weight: bold; margin-top: 20px;");
    mainLayout->addWidget(logLabel);
    
    m_logOutput = new QTextEdit(this);
    m_logOutput->setReadOnly(true);
    m_logOutput->setStyleSheet("background-color: #2c3e50; color: #ecf0f1; font-family: 'Consolas', monospace; padding: 10px;");
    mainLayout->addWidget(m_logOutput);
    
    // 控制按钮
    QHBoxLayout *controlLayout = new QHBoxLayout();
    QPushButton *clearBtn = new QPushButton("清空日志", this);
    clearBtn->setStyleSheet("background-color: #95a5a6; color: white; padding: 8px; border-radius: 4px;");
    connect(clearBtn, &QPushButton::clicked, this, &DemoWindow::clearLog);
    controlLayout->addStretch();
    controlLayout->addWidget(clearBtn);
    
    mainLayout->addLayout(controlLayout);
}

void DemoWindow::setupTestData()
{
    logMessage("🔧 正在设置测试数据...");
    
    // 设置用户权限
    m_permissionManager->setUserRole("admin", PermissionLevel::ADMIN);
    m_permissionManager->setUserRole("operator", PermissionLevel::OPERATOR);
    m_permissionManager->setUserRole("viewer", PermissionLevel::VIEWER);
    
    logMessage("✅ 用户权限设置完成");
    logMessage("   - admin: 管理员权限 (Level 3)");
    logMessage("   - operator: 操作员权限 (Level 2)");
    logMessage("   - viewer: 查看者权限 (Level 1)");
}

void DemoWindow::createTestAuditRecords()
{
    logMessage("📝 正在创建测试审计记录...");
    
    QStringList users = {"admin", "operator", "viewer"};
    QStringList actions = {"Login", "Create", "Update", "Delete", "Export"};
    
    for (int i = 0; i < 10; ++i) {
        AuditLogger::AuditRecord record;
        record.timestamp = QDateTime::currentDateTime().addSecs(-i * 300);
        record.userId = users[i % users.size()];
        record.action = static_cast<AuditLogger::ActionType>(i % 7);
        record.tableName = QString("test_table_%1").arg(i % 3);
        record.recordId = QString("record_%1").arg(i);
        record.oldValue = QString("old_value_%1").arg(i);
        record.newValue = QString("new_value_%1").arg(i);
        record.description = QString("测试审计记录 #%1 - %2").arg(i).arg(actions[i % actions.size()]);
        
        m_auditLogger->logEvent(record);
    }
    
    logMessage("✅ 创建了 10 条测试审计记录");
}

void DemoWindow::testPermissionSystem()
{
    QString userId = m_userCombo->currentText();
    QString permissionText = m_permissionCombo->currentText();
    
    logMessage(QString("🔐 测试用户权限: %1 -> %2").arg(userId, permissionText));
    
    // 转换权限文本到枚举
    PermissionCategory category;
    if (permissionText == "AUDIT_VIEW") category = PermissionCategory::AUDIT_VIEW;
    else if (permissionText == "AUDIT_EXPORT") category = PermissionCategory::AUDIT_EXPORT;
    else if (permissionText == "USER_MANAGEMENT") category = PermissionCategory::USER_MANAGEMENT;
    else if (permissionText == "PLUGIN_MANAGE") category = PermissionCategory::PLUGIN_MANAGE;
    else category = PermissionCategory::AUDIT_VIEW;
    
    // 检查权限
    bool hasPermission = m_permissionManager->hasPermission(userId, category);
    PermissionLevel userLevel = m_permissionManager->getUserPermissionLevel(userId);
    QString userRole = m_permissionManager->getUserRole(userId);
    
    logMessage(QString("   用户等级: Level %1 (%2)").arg(static_cast<int>(userLevel)).arg(userRole));
    logMessage(QString("   权限检查结果: %1").arg(hasPermission ? "✅ 有权限" : "❌ 无权限"));
    
    // 测试权限授予和撤销
    if (!hasPermission && userLevel < PermissionLevel::ADMIN) {
        logMessage("   尝试授予自定义权限...");
        m_permissionManager->grantCustomPermission(userId, "custom.test.permission");
        bool hasCustom = m_permissionManager->hasPermission(userId, "custom.test.permission");
        logMessage(QString("   自定义权限授予结果: %1").arg(hasCustom ? "✅ 成功" : "❌ 失败"));
    }
    
    logMessage("🔐 权限系统测试完成\n");
}

void DemoWindow::testDataExport()
{
    QString format = m_exportFormatCombo->currentText();
    QString outputPath = m_exportPathEdit->text();
    
    if (outputPath.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择导出路径！");
        return;
    }
    
    logMessage(QString("📊 测试数据导出: %1 格式").arg(format));
    logMessage(QString("   导出路径: %1").arg(outputPath));
    
    // 配置导出
    ExportConfig config;
    if (format == "CSV") config.format = ExportFormat::CSV;
    else if (format == "JSON") config.format = ExportFormat::JSON;
    else if (format == "XML") config.format = ExportFormat::XML;
    else if (format == "HTML") config.format = ExportFormat::HTML;
    else config.format = ExportFormat::CSV;
    
    config.outputPath = outputPath;
    config.includeHeaders = true;
    config.filter.startDate = QDateTime::currentDateTime().addDays(-1);
    config.filter.endDate = QDateTime::currentDateTime();
    
    // 验证配置
    QString errorMessage;
    if (!m_dataExporter->validateExportConfig(config, errorMessage)) {
        logMessage(QString("❌ 导出配置验证失败: %1").arg(errorMessage));
        return;
    }
    
    logMessage("   配置验证通过，开始导出...");
    
    // 执行导出
    if (m_dataExporter->exportData(config)) {
        logMessage("✅ 数据导出成功！");
        logMessage(QString("   文件已保存到: %1").arg(outputPath));
        
        // 检查文件大小
        QFileInfo fileInfo(outputPath);
        if (fileInfo.exists()) {
            logMessage(QString("   文件大小: %1 字节").arg(fileInfo.size()));
        }
    } else {
        logMessage("❌ 数据导出失败");
    }
    
    logMessage("📊 数据导出测试完成\n");
}

void DemoWindow::testPluginSystem()
{
    logMessage("🔌 测试插件系统功能");
    
    // 获取可用格式
    QStringList formats = m_dataExporter->getAvailableFormats();
    logMessage(QString("   支持的导出格式: %1").arg(formats.join(", ")));
    
    // 扫描插件
    QString pluginDir = QCoreApplication::applicationDirPath() + "/plugins";
    QStringList foundPlugins = m_pluginSystem->scanForPlugins(pluginDir);
    logMessage(QString("   扫描插件目录: %1").arg(pluginDir));
    logMessage(QString("   发现插件数量: %1").arg(foundPlugins.size()));
    
    if (!foundPlugins.isEmpty()) {
        for (const QString &plugin : foundPlugins) {
            logMessage(QString("   - %1").arg(QFileInfo(plugin).fileName()));
        }
    }
    
    // 获取插件信息
    QList<PluginInfo> availablePlugins = m_pluginSystem->getAvailablePlugins();
    logMessage(QString("   可用插件数量: %1").arg(availablePlugins.size()));
    
    // 测试插件权限
    logMessage("   测试插件权限管理:");
    // Check plugin permissions instead of registering (method doesn't exist)
    QStringList requiredPermissions;
    requiredPermissions << "plugin.test.access";
    bool hasPermissions = m_pluginSystem->checkPluginPermissions("test_plugin", requiredPermissions);
    m_logOutput->append(QString("Plugin permissions check: %1").arg(hasPermissions ? "PASSED" : "FAILED"));
    bool canAccess = m_permissionManager->canAccessPlugin("admin", "test_plugin");
    logMessage(QString("   管理员访问测试插件: %1").arg(canAccess ? "✅ 允许" : "❌ 拒绝"));
    
    // 测试外部集成
    logMessage("   测试外部应用集成:");
    bool registered = m_pluginSystem->registerAsExternalPlugin("DemoApplication");
    logMessage(QString("   注册为外部插件: %1").arg(registered ? "✅ 成功" : "❌ 失败"));
    
    logMessage("🔌 插件系统测试完成\n");
}

void DemoWindow::clearLog()
{
    m_logOutput->clear();
    logMessage("🧹 日志已清空");
}

void DemoWindow::logMessage(const QString &message)
{
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString formattedMessage = QString("[%1] %2").arg(timestamp, message);
    m_logOutput->append(formattedMessage);
    
    // 自动滚动到底部
    QTextCursor cursor = m_logOutput->textCursor();
    cursor.movePosition(QTextCursor::End);
    m_logOutput->setTextCursor(cursor);
    
    // 输出到控制台
    qDebug() << formattedMessage;
}

// 主函数
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    
    app.setApplicationName("AuditTrailSystemDemo");
    app.setApplicationVersion("1.0.0");
    app.setOrganizationName("AuditTrail Team");
    
    DemoWindow window;
    window.show();
    
    return app.exec();
}

#include "demo_main.moc"